#coding=utf-8
import json
import os
import re
import logging

import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()
import logging
import re
from tbitem import models

server_logger = logging.getLogger("server")
import sys
import time
from urllib.parse import urlencode
import requests
def getRandomLinkJsonData():
    with open('RandomLink.json', 'r',encoding='utf-8') as f:
        jsons = json.load(f)
        # print(jsons)
    return jsons
class ContentConfig:
    def __init__(self):
        '''shenhuawade账号!!!----Start'''
        self.bokeeName = 'zenmeyangya'
        self.username = '111325433@qq.com'
        self.password = '11987wade'
        self.title = '默认配置'
        self.content = '默认配置'
        self.columnName = ''  # 分类名字1
        self.addType = '值得买'  # 分类2
        self.tags = ''  # 标签
        self.brief = ''  # 内容摘要
    def getACCOUNT(self,username):
        qibo_Account = models.QiBoAccount.objects.filter(username=username).first()
        print(qibo_Account)
        if not qibo_Account:

            return self
        else:return qibo_Account

def bokeePOST(Config):

    try:
        loginUrl = 'http://tefenxiang.blog.bokee.net/usermodule/userManager_quickLogin.do'
        formdata1 = {
            'username': Config.username,
            'password': Config.password
        }
        headers={
            'Content-Type':'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
        }
        session = requests.session()
        html1 = session.post(loginUrl,data=formdata1,headers=headers, timeout=10)  # 登录
        print(f'登录状态: {html1.status_code}')
        # print(html1.history)
        # print(html1.headers)
        # print(html1.cookies)

        # exit()
        # # 获取文章列表
        # contentlist = session.get(url = 'http://www.bokee.net/bloggermodule/blogadmin2_listblog.do')
        # print(contentlist.text)


        postContentUrl = 'http://tefenxiang.blog.bokee.net/bloggermodule/blogadmin2_saveblog.do'
        formdata2 = {
            'bokeeName': Config.bokeeName,
            'id': '',
            'action': 'saveEntry',
            'title': Config.title,
            'content': Config.content,
            'columnName': Config.columnName,
            'addType': Config.addType,
            'tags': Config.tags,
            'brief': Config.brief,
            'visibility': '100',  # 公开方式，保持默认
            'commentable': '1',  # 开启评论，保持默认
            'displayControl': '2',  # 摘要模式，保持默认
            'stateNo': '1'  # 状态码，保持默认
        }
        html2 = session.post(postContentUrl, formdata2,headers=headers, timeout=10)
        htmltexts = html2.text
        # server_logger.error(htmltexts)
        # print(htmltexts)


        finderrorpage = re.compile('非常抱歉！你超出使用限制了！')
        result = finderrorpage.findall(htmltexts)


        if result != []:
            server_logger.error('检测html--发帖使用超出限制')
            raise Exception("发帖使用超出限制")  #真正检测发够了
        print('发布')
        restr = re.compile('<input type="hidden" name="id" value="(\d+)">')
        contentid = restr.findall(htmltexts)

        #敏感词过滤捕捉
        findMinGanPage = re.compile("你发布的内容可能有敏感信息")
        findMinGanPage_result = findMinGanPage.findall(htmltexts)
        if findMinGanPage_result != []:
            print('发布的内容可能有敏感信息')
            return True   #虽然是敏感信息了,但是还是发布成功,返回正确True,不在进行下面的组合

        print('发表后的页面id内容是:')
        # print(html2.text)
        print(contentid)  #可能是空的[]

        if contentid[0] != "0":
            # RandomLinkJson = getRandomLinkJsonData()
            # RandomLinkJson[contentid[0]] = Config.title[0]
            # json.dump(RandomLinkJson, open(r'RandomLink.json', 'w'))
            # print(f"成功将{contentid}文章加入链轮库")
            server_logger.error('检测html--成功发布')
        else:
            server_logger.error("淘宝商品可能有错误")

        #保存发帖链接,发帖标题为json


        return True
    except Exception as e:
        print(e)
        server_logger.error('发布错误结束')
        return False




if __name__ == '__main__':
    # # 调用企业博客发帖模块函数块需要的内容----START
    # bokeeconfig =ContentConfig()
    # bokeeconfig.title = '【图文体验】峰米Smart评价怎么样？？觉得峰米投影仪好不好123'
    # bokeeconfig.content = '图文体验】峰米Smart评价怎么样？？觉得峰米投影仪好不好12'
    # bokeeconfig.columnName = '值得买'  # 分类名字1
    # bokeeconfig.addType = '值得买'  # 分类2
    # bokeeconfig.tags = ''  # 标签
    # bokeeconfig.brief = ''  # 内容摘要
    # bokeePOST(bokeeconfig)
    # print(bokeeconfig.__dict__)
    # # 调用企业博客发帖模块函数块需要的内容----END
    wade = ContentConfig()
    print(wade.getACCOUNT('11325433@qq.com').__dict__)
    bokeePOST(wade.getACCOUNT('11325433@qq.com'))





